<template>
    <span v-if="props.formate">{{ currentNumber.toLocaleString()  }}</span>
    <span v-else>{{ currentNumber }}</span>
  
  </template>
  
  <script setup lang="ts">
  import { ref, watch } from 'vue';
  interface Props {
      number: number | string
      formate: boolean
  }
  const props = defineProps<Props>()
  const currentNumber = ref(0);
  // 动画数字
  const animateNumber = (target: Props['number'] = 0, duration: Props['number'] = 0) => {
      let i = 50
      let n = 0
      currentNumber.value = Number(duration)
      let spread = Number(target) - Number(duration)
      let step = spread / i
      if(haveMinder(target)) { n = 2 }
      let timer = () => setTimeout(() => {
        i--
        if (i > 0) {
              currentNumber.value = Number((currentNumber.value + step).toFixed(n))
              timer()
          } else {
              currentNumber.value = Number(target)
              clearTimeout(timer())
          }
      }, (30-i)*2)
      timer()
  };
  // 是否有小数
  const haveMinder = (n:Props['number']) => { return (n+'').includes('.') }
  // 监听数字变化
  watch(() => props.number, (newVal, oldVal) => {
      animateNumber(newVal, oldVal);
  })
  
  </script>
  
  